﻿using JESAI.Application.Abstractions.Admin.Dtos.Config;
using JESAI.Application.Abstractions.Auth.Dtos;
using JESAI.Application.Abstractions.Sys;
using JESAI.AutoMapper.ObjectMapping;
using JESAI.Biz.Data.Commons.Consts;
using JESAI.Caching;
using JESAI.Core.Attributes;
using JESAI.Platform.Domain.Admin.Entities;
using JESAI.Platform.Domain.Admin.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Application.Service.Sys
{
    [AppService]
    public class AppService: IAppService
    {
        private readonly IAppRepository _appRepository;
        private readonly CacheManager _cacheManager;
        public AppService(
            IAppRepository appRepository,
            CacheManager cacheManager) 
        {
            _appRepository=appRepository;
            _cacheManager=cacheManager;
        }

        public AppInfoDto GetAppByKey(string key)
        {
            AppModel appModel = _cacheManager.GetOrAdd<AppModel>(CacheConst.AppCacheKeyPrefix + key, (val) =>
            {
                return _appRepository.GetFirst(p => p.AppId == key);
            });

            return appModel.MapTo<AppInfoDto>();
        }

        public List<AppInfoDto> QueryAppList()
        {
           var modelList= _appRepository._DbQueryable.ToList();
           return modelList.MapTo<List<AppInfoDto>>();
        }

        public void UpdateOrInsert(SetAppInfoInput input)
        {
            var model = input.MapTo<AppModel>();
            if (model.Id > 0)
            {
                // 基础字段不容许更新
                _appRepository.AsUpdateable(model).ExecuteCommand();
            }
            else
            {
                _appRepository.AsInsertable(model).ExecuteCommand();
            }
        }
    }
}
